<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/2/002
 * Time: 16:55
 */

namespace app\api\controller\v1;

use app\api\model\Address as AddressModel;
use app\api\service\Token;
use app\api\validate\AddressValidate;
use app\api\validate\IDMustBePostiveInt;
use app\lib\exception\AddressException;
use app\lib\exception\SuccessMessage;


class Address {

    /**
     * 收货地址列表
     * @return mixed
     */
    public function addressList() {

        $address = AddressModel::getAddressList();
        if ($address->isEmpty()) {
            return [];
        }

        return $address;
    }

    /**
     * 收货地址详情
     * @param $id
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws AddressException
     */
    public function addressInfo($id) {
        (new IDMustBePostiveInt())->goCheck();

        $uid = Token::getCurrentUid();

        $address = AddressModel::getAddressInfoById($id, $uid);
        if (!$address) {
            throw new AddressException();
        }

        return $address;
    }

    /**
     * 创建或者更新收货地址
     * @return SuccessMessage
     */
    public function createOrUpdateAddress() {
        if (input('param.id', 0) > 0) {
            (new IDMustBePostiveInt())->goCheck();
        }

        $AddressValidate = new AddressValidate();
        $AddressValidate->goCheck();
        $params = $AddressValidate->getDataByRule(input('post.'));
        $params['id'] = input('param.id');

        AddressModel::createOrUpdateAddress($params);
        return new SuccessMessage();
    }

    /**
     * 删除收货地址
     * @return SuccessMessage
     */
    public function deleteAddress() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');
        AddressModel::deleteAddress($id);
        return new SuccessMessage();
    }

    /**
     * 设置默认地址
     * @return SuccessMessage
     */
    public function setDefaultAddress() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');
        AddressModel::setDefaultAddress($id);
        return new SuccessMessage();
    }
}